﻿using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;

using GameCommon.ComponentInterfaces;
using GameCommon.Manager;
using GameCommon.ServiceInterfaces;

using Menu.Components;

using Microsoft.Xna.Framework;

namespace Menu.Screens.Countdown
{
    internal class CountAnimation : IAnimation
    {
        private readonly ISplineEffectService splineEffect;

        private readonly Text text;

        private double elapsed;

        private readonly int height;

        private readonly int duration;

        private bool IsMovementFinished;

        private int? offset;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="text"></param>
        /// <param name="offset">in Milliseconds</param>
        /// <param name="duration">in Milliseconds</param>
        public CountAnimation(Text text, int offset, int duration)
        {
            this.text = text;
            this.offset = offset;
            this.duration = duration;
            this.height = (Managers.ContentManager.GetViewportHeight() / 2) - (text.Size.Height / 2);
            this.splineEffect = GameCommon.Services.Service.SplineEffectService;
        }

        public bool IsFinished { get; private set; }

        public void Update(GameTime gameTime)
        {
            if (this.IsFinished)
            {
                return;
            }

            this.elapsed += gameTime.ElapsedGameTime.Milliseconds;

            if (!IsMovementFinished)
            {
                this.Movement();
                return;
            }

            this.FadeOut();

        }

        private void FadeOut()
        {
            if (this.text.Opacity > 0)
            {
                this.text.Opacity -= 0.1f;
                return;
            }

            this.IsFinished = true;
        }

        private void Movement()
        {
            if (this.offset != null)
            {
                if (this.elapsed < this.offset)
                {
                    return;
                }

                this.elapsed = 0;
                this.offset = null;
                this.text.Opacity = 1;
                return;
            }

            if (this.elapsed > this.duration)
            {
                this.IsMovementFinished = true;
                return;
            }

            this.text.Position.Y = Convert.ToInt32(this.splineEffect.CubicEaseInOut(this.elapsed / 1000.0, 0, this.height, this.duration / 1000.0));
        }
    }
}